<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-semibold text-gray-800">借还管理</h2>
      <button @click="$router.push('/equipment-borrow/form')" class="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
        <HandRaisedIcon class="h-5 w-5 mr-2" />
        设备借用
      </button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
      <form @submit.prevent="handleSearch" class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label for="equipmentName" class="block text-sm font-medium text-gray-700">设备名称</label>
          <input type="text" id="equipmentName" v-model="searchForm.equipmentName" placeholder="请输入设备名称" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div>
          <label for="borrowerName" class="block text-sm font-medium text-gray-700">借用人</label>
          <input type="text" id="borrowerName" v-model="searchForm.borrowerName" placeholder="请输入借用人姓名" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div>
          <label for="status" class="block text-sm font-medium text-gray-700">借用状态</label>
          <select id="status" v-model="searchForm.status" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">请选择状态</option>
            <option value="BORROWED">借用中</option>
            <option value="RETURNED">已归还</option>
            <option value="OVERDUE">已超期</option>
          </select>
        </div>
        <div>
          <label for="borrowDate" class="block text-sm font-medium text-gray-700">借用日期</label>
          <input type="date" id="borrowDate" v-model="searchForm.borrowDate" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div class="md:col-span-4 flex justify-end space-x-3 mt-4">
          <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">搜索</button>
          <button type="button" @click="handleReset" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">重置</button>
        </div>
      </form>
    </div>

    <!-- 借还记录列表 -->
    <div class="bg-white rounded-xl shadow-lg p-6">
      <div v-if="loading" class="text-center py-8">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
        <p class="mt-2 text-gray-500">加载中...</p>
      </div>
      <div v-else class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">设备名称</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">设备编号</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">借用人</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">借用时间</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">预计归还</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">实际归还</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="record in borrowRecords" :key="record.id">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ record.equipmentName }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.equipmentCode }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.borrowerName }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.borrowDate }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.expectedReturnDate }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.actualReturnDate || '-' }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                <span :class="['px-2 inline-flex text-xs leading-5 font-semibold rounded-full', getStatusClass(record.status)]">
                  {{ getStatusText(record.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewDetail(record)" class="text-indigo-600 hover:text-indigo-900 mr-3">查看</button>
                <button @click="returnEquipment(record)" v-if="record.status === 'BORROWED'" class="text-green-600 hover:text-green-900">归还</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="flex justify-end mt-6">
        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
          <button @click="handleCurrentChange(pagination.current - 1)" :disabled="pagination.current === 1" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
            <span class="sr-only">Previous</span>
            <ChevronLeftIcon class="h-5 w-5" aria-hidden="true" />
          </button>
          <button v-for="page in totalPages" :key="page" @click="handleCurrentChange(page)" :class="['relative inline-flex items-center px-4 py-2 border text-sm font-medium', page === pagination.current ? 'z-10 bg-indigo-50 border-indigo-500 text-indigo-600' : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50']">
            {{ page }}
          </button>
          <button @click="handleCurrentChange(pagination.current + 1)" :disabled="pagination.current === totalPages" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
            <span class="sr-only">Next</span>
            <ChevronRightIcon class="h-5 w-5" aria-hidden="true" />
          </button>
        </nav>
        <div class="ml-4 flex items-center text-sm text-gray-700">
          <span>共 {{ pagination.total }} 条</span>
          <select v-model="pagination.size" @change="handleSizeChange($event.target.value)" class="ml-2 block w-auto pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
            <option :value="10">10 条/页</option>
            <option :value="20">20 条/页</option>
            <option :value="50">50 条/页</option>
            <option :value="100">100 条/页</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 归还对话框 -->
    <div v-if="showReturnDialog" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3">
          <h3 class="text-lg font-medium text-gray-900 mb-4">设备归还</h3>
          <div class="mb-4">
            <p class="text-sm text-gray-600">设备：{{ selectedRecord?.equipmentName }}</p>
            <p class="text-sm text-gray-600">借用人：{{ selectedRecord?.borrowerName }}</p>
            <p class="text-sm text-gray-600">借用时间：{{ selectedRecord?.borrowDate }}</p>
          </div>
          <div class="mb-4">
            <label for="returnCondition" class="block text-sm font-medium text-gray-700">归还状态</label>
            <select id="returnCondition" v-model="returnForm.condition" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
              <option value="GOOD">完好</option>
              <option value="DAMAGED">损坏</option>
              <option value="LOST">丢失</option>
            </select>
          </div>
          <div class="mb-4">
            <label for="returnNote" class="block text-sm font-medium text-gray-700">备注</label>
            <textarea id="returnNote" v-model="returnForm.note" rows="3" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="请输入备注信息"></textarea>
          </div>
          <div class="flex justify-end space-x-3">
            <button @click="closeReturnDialog" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
              取消
            </button>
            <button @click="confirmReturn" :disabled="returnLoading" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50">
              {{ returnLoading ? '处理中...' : '确认归还' }}
            </button>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { HandRaisedIcon, ChevronLeftIcon, ChevronRightIcon } from '@heroicons/vue/24/outline'
import request from '@/utils/request'

const router = useRouter()

const borrowRecords = ref([])
const loading = ref(false)
const showReturnDialog = ref(false)
const selectedRecord = ref(null)
const returnLoading = ref(false)

const searchForm = reactive({
  equipmentName: '',
  borrowerName: '',
  status: '',
  borrowDate: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const returnForm = reactive({
  condition: 'GOOD',
  note: ''
})

const totalPages = computed(() => Math.ceil(pagination.total / pagination.size))

// 获取状态样式
const getStatusClass = (status) => {
  const statusMap = {
    'BORROWED': 'bg-yellow-100 text-yellow-800',
    'RETURNED': 'bg-green-100 text-green-800',
    'OVERDUE': 'bg-red-100 text-red-800'
  }
  return statusMap[status] || 'bg-gray-100 text-gray-800'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'BORROWED': '借用中',
    'RETURNED': '已归还',
    'OVERDUE': '已超期'
  }
  return statusMap[status] || status
}

// 查看详情
const viewDetail = (record) => {
  router.push(`/equipment-borrow/detail/${record.id}`)
}

// 归还设备
const returnEquipment = (record) => {
  selectedRecord.value = record
  showReturnDialog.value = true
}


// 关闭归还对话框
const closeReturnDialog = () => {
  showReturnDialog.value = false
  selectedRecord.value = null
  Object.assign(returnForm, {
    condition: 'GOOD',
    note: ''
  })
}


// 确认归还
const confirmReturn = async () => {
  try {
    returnLoading.value = true
    
    const returnData = {
      borrowId: selectedRecord.value.id,
      returnDate: new Date().toISOString(),
      remark: returnForm.note
    }
    
    await request.post('/equipment-borrow/return', returnData)
    
    showMessage('设备归还成功', 'success')
    closeReturnDialog()
    loadBorrowRecords()
    
  } catch (error) {
    console.error('归还设备失败:', error)
    showMessage('归还设备失败', 'error')
  } finally {
    returnLoading.value = false
  }
}


// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadBorrowRecords()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    equipmentName: '',
    borrowerName: '',
    status: '',
    borrowDate: ''
  })
  pagination.current = 1
  loadBorrowRecords()
}

// 页面大小改变
const handleSizeChange = (size) => {
  pagination.size = parseInt(size)
  pagination.current = 1
  loadBorrowRecords()
}

// 当前页改变
const handleCurrentChange = (current) => {
  if (current < 1 || current > totalPages.value) return
  pagination.current = current
  loadBorrowRecords()
}

// 加载借还记录
const loadBorrowRecords = async () => {
  try {
    loading.value = true
    
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      status: searchForm.status || undefined,
      borrowDateStart: searchForm.borrowDate ? new Date(searchForm.borrowDate).toISOString() : undefined
    }

    const response = await request.get('/equipment-borrow/list', { params })
    borrowRecords.value = response.data.records.map(record => ({
      id: record.id,
      equipmentName: record.equipmentName,
      equipmentCode: record.equipmentCode,
      borrowerName: record.borrowerName,
      borrowDate: record.borrowTime,
      expectedReturnDate: record.expectedReturnTime,
      actualReturnDate: record.actualReturnTime,
      status: record.status
    }))
    pagination.total = response.data.total
    
  } catch (error) {
    console.error('加载借还记录失败:', error)
    showMessage('加载借还记录失败', 'error')
  } finally {
    loading.value = false
  }
}

// 简单消息显示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

onMounted(() => {
  loadBorrowRecords()
})
</script>